<template>
  <div class="base-table">
    <!-- 表格头部工具栏 -->
    <div class="table-header" v-if="showHeader">
      <div class="header-left">
        <!-- 批量操作 -->
        <div class="batch-actions" v-if="selectedRows.length > 0">
          <slot name="batch-actions" :selectedRows="selectedRows" />
        </div>
      </div>
      
      <div class="header-right">
        <!-- 列设置 -->
        <el-dropdown 
          v-if="showColumnSettings" 
          trigger="click" 
          @command="handleColumnCommand"
        >
          <el-button size="small" circle>
            <el-icon><Setting /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="reset">重置列设置</el-dropdown-item>
              <el-dropdown-item command="save">保存当前设置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <!-- 刷新按钮 -->
        <el-button 
          v-if="showRefresh" 
          size="small" 
          circle 
          @click="handleRefresh"
        >
          <el-icon><Refresh /></el-icon>
        </el-button>
        
        <!-- 密度设置 -->
        <el-dropdown 
          v-if="showDensity" 
          trigger="click" 
          @command="handleDensityChange"
        >
          <el-button size="small" circle>
            <el-icon><Grid /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-for="density in densityOptions" 
                :key="density.value"
                :command="density.value"
                :class="{ 'is-active': tableDensity === density.value }"
              >
                {{ density.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 列设置面板 -->
    <el-drawer
      v-model="showColumnSettingPanel"
      title="列设置"
      direction="rtl"
      size="400px"
    >
      <div class="column-setting-panel">
        <div class="column-group" v-for="group in columnGroups" :key="group.key">
          <div class="group-header" v-if="group.title">
            <el-checkbox 
              :model-value="isGroupAllChecked(group)" 
              @change="(val: boolean) => toggleGroup(group, val)"
            >
              {{ group.title }}
            </el-checkbox>
          </div>
          <div class="column-list">
            <draggable 
              v-model="group.columns" 
              item-key="key"
              handle=".drag-handle"
              @end="handleColumnDragEnd"
            >
              <template #item="{ element }">
                <div class="column-item" :class="{ 'hidden': !element.visible }">
                  <el-checkbox 
                    v-model="element.visible" 
                    @change="(val: boolean) => handleColumnVisibilityChange(element, val)"
                  >
                    {{ element.title }}
                  </el-checkbox>
                  <div class="column-actions">
                    <el-icon class="drag-handle"><Rank /></el-icon>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="column-setting-footer">
          <el-button @click="resetColumnSettings">重置</el-button>
          <el-button type="primary" @click="saveColumnSettings">保存</el-button>
        </div>
      </template>
    </el-drawer>
    
    <!-- 表格主体 -->
    <div 
      class="table-container" 
      :class="[`table-density-${tableDensity}`, { 'table-bordered': bordered }]"
    >
      <el-table
        ref="tableRef"
        :data="processedData"
        :height="height"
        :max-height="maxHeight"
        :border="bordered"
        :stripe="stripe"
        :highlight-current-row="highlightCurrentRow"
        :row-class-name="rowClassName"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @filter-change="handleFilterChange"
        @row-click="handleRowClick"
        v-loading="loading"
        :element-loading-text="loadingText"
      >
        <!-- 选择列 -->
        <el-table-column 
          v-if="showSelection" 
          type="selection" 
          width="50"
          fixed="left"
        />
        
        <!-- 序号列 -->
        <el-table-column 
          v-if="showIndex" 
          type="index" 
          label="#" 
          width="60"
          fixed="left"
        />
        
        <!-- 数据列 -->
        <template v-for="column in visibleColumns" :key="column.prop || column.key">
          <el-table-column
            :prop="column.prop || column.key"
            :label="column.label || column.title"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :sortable="column.sortable"
            :sort-orders="column.sortOrders"
            :filters="column.filters"
            :filter-method="column.filterMethod"
            :filter-multiple="column.filterMultiple"
            :show-overflow-tooltip="column.showOverflowTooltip !== false"
            :align="column.align || 'left'"
            :header-align="column.headerAlign || column.align || 'left'"
            :class-name="column.className"
            :label-class-name="column.labelClassName"
          >
            <template #default="{ row, $index }">
              <slot 
                :name="`column-${column.prop || column.key}`" 
                :row="row" 
                :column="column" 
                :index="$index"
                :value="getColumnValue(row, column)"
              >
                <span v-if="column.formatter">
                  {{ column.formatter(getColumnValue(row, column), row, column, $index) }}
                </span>
                <span v-else>
                  {{ getColumnValue(row, column) }}
                </span>
              </slot>
            </template>
          </el-table-column>
        </template>
        
        <!-- 操作列 -->
        <el-table-column
          v-if="showActionColumn"
          :label="actionColumnTitle"
          :width="actionColumnWidth"
          :fixed="actionColumnFixed"
          class-name="action-column"
        >
          <template #default="{ row, $index }">
            <slot 
              name="actions" 
              :row="row" 
              :index="$index"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="table-pagination" v-if="showPagination && total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        :layout="paginationLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { 
  ref, 
  computed, 
  watch, 
  onMounted, 
  nextTick,
  useAttrs
} from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import { Setting, Refresh, Grid, Rank } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'

// 定义组件属性
interface Column {
  key?: string
  prop?: string
  title: string
  label?: string
  width?: string | number
  minWidth?: string | number
  fixed?: boolean | 'left' | 'right'
  sortable?: boolean | 'custom'
  sortOrders?: ('ascending' | 'descending')[]
  filters?: Array<{ text: string; value: any }>
  filterMethod?: (value: any, row: any, column: any) => boolean
  filterMultiple?: boolean
  showOverflowTooltip?: boolean
  align?: 'left' | 'center' | 'right'
  headerAlign?: 'left' | 'center' | 'right'
  className?: string
  labelClassName?: string
  visible?: boolean
  formatter?: (value: any, row: any, column: any, index: number) => any
  group?: string
}

interface ColumnGroup {
  key: string
  title?: string
  columns: Column[]
}

interface Props {
  // 数据相关
  data: any[]
  columns: Column[]
  loading?: boolean
  loadingText?: string
  
  // 表格配置
  height?: string | number
  maxHeight?: string | number
  bordered?: boolean
  stripe?: boolean
  highlightCurrentRow?: boolean
  rowClassName?: (row: any, rowIndex: number) => string
  
  // 功能开关
  showHeader?: boolean
  showSelection?: boolean
  showIndex?: boolean
  showPagination?: boolean
  showColumnSettings?: boolean
  showRefresh?: boolean
  showDensity?: boolean
  showActionColumn?: boolean
  
  // 分页配置
  total?: number
  pageSizes?: number[]
  paginationLayout?: string
  currentPage?: number
  pageSize?: number
  
  // 操作列配置
  actionColumnTitle?: string
  actionColumnWidth?: string | number
  actionColumnFixed?: boolean | 'left' | 'right'
  
  // 状态管理
  storageKey?: string
}

// 默认属性
const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  columns: () => [],
  loading: false,
  loadingText: '加载中...',
  bordered: false,
  stripe: false,
  highlightCurrentRow: false,
  showHeader: true,
  showSelection: false,
  showIndex: false,
  showPagination: true,
  showColumnSettings: true,
  showRefresh: true,
  showDensity: true,
  showActionColumn: false,
  total: 0,
  pageSizes: () => [10, 20, 30, 50, 100],
  paginationLayout: 'total, sizes, prev, pager, next, jumper',
  currentPage: 1,
  pageSize: 20,
  actionColumnTitle: '操作',
  actionColumnWidth: 150,
  actionColumnFixed: 'right',
  storageKey: 'base-table-config'
})

// 定义事件
const emit = defineEmits<{
  (e: 'update:currentPage', value: number): void
  (e: 'update:pageSize', value: number): void
  (e: 'selection-change', value: any[]): void
  (e: 'sort-change', value: { column: any; prop: string; order: string }): void
  (e: 'filter-change', value: any): void
  (e: 'row-click', value: any): void
  (e: 'refresh'): void
  (e: 'page-change', value: { currentPage: number; pageSize: number }): void
}>()

// 响应式数据
const tableRef = ref()
const selectedRows = ref<any[]>([])
const showColumnSettingPanel = ref(false)
const tableDensity = ref<'default' | 'medium' | 'small' | 'mini'>('default')
const densityOptions = [
  { label: '默认', value: 'default' },
  { label: '中等', value: 'medium' },
  { label: '紧凑', value: 'small' },
  { label: '迷你', value: 'mini' }
]

// 分页相关
// 移除defineModel，使用传统的props和emit方式
const currentPage = computed({
  get: () => props.currentPage,
  set: (val) => emit('update:currentPage', val)
})

const pageSize = computed({
  get: () => props.pageSize,
  set: (val) => emit('update:pageSize', val)
})

// 列配置相关
const columnConfig = ref<Column[]>([])
const columnGroups = ref<ColumnGroup[]>([])

// 初始化列配置
const initColumnConfig = () => {
  // 从localStorage加载配置
  const savedConfig = loadColumnConfig()
  
  // 处理列配置
  const processedColumns = props.columns.map((col: Column) => {
    const savedCol = savedConfig?.find((c: any) => c.key === (col.key || col.prop))
    return {
      visible: true,
      ...col,
      ...(savedCol || {})
    }
  })
  
  // 按组分类列
  const groups: Record<string, Column[]> = {}
  processedColumns.forEach((col: Column) => {
    const groupKey = col.group || 'default'
    if (!groups[groupKey]) {
      groups[groupKey] = []
    }
    groups[groupKey].push(col)
  })
  
  // 转换为组结构
  columnGroups.value = Object.keys(groups).map(key => ({
    key,
    title: getColumnGroupTitle(key),
    columns: groups[key]
  }))
  
  columnConfig.value = processedColumns
}

// 获取列组标题
const getColumnGroupTitle = (groupKey: string) => {
  const groupTitles: Record<string, string> = {
    default: '',
    basic: '基本信息',
    finance: '财务信息',
    status: '状态信息',
    action: '操作信息'
  }
  return groupTitles[groupKey] || ''
}

// 加载列配置
const loadColumnConfig = () => {
  try {
    const configStr = localStorage.getItem(`${props.storageKey}-columns`)
    return configStr ? JSON.parse(configStr) : null
  } catch (error) {
    console.warn('Failed to load column config:', error)
    return null
  }
}

// 保存列配置
const saveColumnConfig = () => {
  try {
    const config = columnConfig.value.map(col => ({
      key: col.key || col.prop,
      visible: col.visible,
      width: col.width
    }))
    localStorage.setItem(`${props.storageKey}-columns`, JSON.stringify(config))
  } catch (error) {
    console.warn('Failed to save column config:', error)
  }
}

// 计算属性
const visibleColumns = computed(() => {
  return columnConfig.value.filter(col => col.visible !== false)
})

const processedData = computed(() => {
  return props.data
})

const isGroupAllChecked = (group: ColumnGroup) => {
  return group.columns.every(col => col.visible)
}

// 方法
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

const handleSortChange = (sortInfo: { column: any; prop: string; order: string }) => {
  emit('sort-change', sortInfo)
}

const handleFilterChange = (filters: any) => {
  emit('filter-change', filters)
}

const handleRowClick = (row: any, column: any, event: any) => {
  emit('row-click', row)
}

const handleRefresh = () => {
  emit('refresh')
}

const handleDensityChange = (density: 'default' | 'medium' | 'small' | 'mini') => {
  tableDensity.value = density
}

const handleColumnCommand = (command: string) => {
  switch (command) {
    case 'reset':
      resetColumnSettings()
      break
    case 'save':
      saveColumnSettings()
      break
  }
}

const toggleGroup = (group: ColumnGroup, checked: boolean) => {
  group.columns.forEach(col => {
    col.visible = checked
  })
}

const handleColumnVisibilityChange = (column: Column, visible: boolean) => {
  column.visible = visible
}

const handleColumnDragEnd = () => {
  // 重新计算列顺序
  const allColumns: Column[] = []
  columnGroups.value.forEach(group => {
    allColumns.push(...group.columns)
  })
  columnConfig.value = allColumns
}

const resetColumnSettings = () => {
  initColumnConfig()
  ElMessage.success('列设置已重置')
}

const saveColumnSettings = () => {
  saveColumnConfig()
  showColumnSettingPanel.value = false
  ElMessage.success('列设置已保存')
}

const handleSizeChange = (size: number) => {
  emit('update:pageSize', size)
  emit('page-change', { currentPage: props.currentPage, pageSize: size })
}

const handleCurrentChange = (page: number) => {
  emit('update:currentPage', page)
  emit('page-change', { currentPage: page, pageSize: props.pageSize })
}

// 修复getRowValue方法，确保能正确处理各种字段命名
const getRowValue = (row: any, key: string) => {
  // 添加调试日志
  console.log('getRowValue called with:', { row, key });
  
  // 如果直接能找到key，直接返回
  if (row[key] !== undefined) {
    console.log('直接找到key:', key, 'value:', row[key]);
    return row[key];
  }
  
  // 尝试将下划线命名转换为驼峰命名
  const camelCaseKey = key.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
  if (row[camelCaseKey] !== undefined) {
    console.log('通过驼峰命名找到:', camelCaseKey, 'value:', row[camelCaseKey]);
    return row[camelCaseKey];
  }
  
  // 尝试将驼峰命名转换为下划线命名
  const underscoreKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
  if (row[underscoreKey] !== undefined) {
    console.log('通过下划线命名找到:', underscoreKey, 'value:', row[underscoreKey]);
    return row[underscoreKey];
  }
  
  // 使用原来的逻辑作为备选
  const result = key.split('.').reduce((obj, k) => obj?.[k], row);
  console.log('通过点分隔符找到:', key, 'value:', result);
  return result;
}

// 添加getColumnValue方法以匹配AdvancedTable的接口
const getColumnValue = (row: any, column: Column) => {
  // 添加调试日志
  console.log('getColumnValue called with:', { row, column });
  
  const prop = column.prop || column.key || '';
  
  // 如果直接能找到prop，直接返回
  if (row[prop] !== undefined) {
    console.log('直接找到prop:', prop, 'value:', row[prop]);
    return row[prop];
  }
  
  // 尝试将下划线命名转换为驼峰命名
  const camelCaseProp = prop.replace(/_([a-z])/g, (g: string) => g[1].toUpperCase());
  if (row[camelCaseProp] !== undefined) {
    console.log('通过驼峰命名找到:', camelCaseProp, 'value:', row[camelCaseProp]);
    return row[camelCaseProp];
  }
  
  // 尝试将驼峰命名转换为下划线命名
  const underscoreProp = prop.replace(/([A-Z])/g, '_$1').toLowerCase();
  if (row[underscoreProp] !== undefined) {
    console.log('通过下划线命名找到:', underscoreProp, 'value:', row[underscoreProp]);
    return row[underscoreProp];
  }
  
  console.log('未找到对应值，返回原始prop值:', row[prop]);
  return row[prop];
}

// 生命周期
onMounted(() => {
  initColumnConfig()
})

// 监听器
watch(() => props.columns, () => {
  initColumnConfig()
}, { deep: true })

// 暴露方法
defineExpose({
  tableRef,
  selectedRows,
  refresh: handleRefresh
})
</script>

<style scoped lang="scss">
.base-table {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 8px 0;
    
    .header-left,
    .header-right {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  
  .column-setting-panel {
    padding: 20px;
    
    .column-group {
      margin-bottom: 20px;
      
      .group-header {
        margin-bottom: 10px;
        padding-bottom: 8px;
        border-bottom: 1px solid #ebeef5;
      }
      
      .column-list {
        .column-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 8px 12px;
          border-radius: 4px;
          margin-bottom: 4px;
          transition: all 0.3s;
          
          &:hover {
            background-color: #f5f7fa;
          }
          
          &.hidden {
            opacity: 0.6;
          }
          
          .column-actions {
            .drag-handle {
              cursor: move;
              color: #909399;
            }
          }
        }
      }
    }
  }
  
  .column-setting-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
  }
  
  .table-container {
    &.table-density {
      &-medium {
        :deep(.el-table__cell) {
          padding: 8px 0;
        }
      }
      
      &-small {
        :deep(.el-table__cell) {
          padding: 6px 0;
        }
      }
      
      &-mini {
        :deep(.el-table__cell) {
          padding: 4px 0;
        }
      }
    }
    
    &.table-bordered {
      :deep(.el-table__cell) {
        border-right: 1px solid #ebeef5;
      }
    }
  }
  
  .table-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.action-column) {
    .cell {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}
</style>